package com.zygk.qybofficial.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import com.common.zxing.CaptureActivity;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.DateUtil;
import com.zygk.library.util.Hardware;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.qybofficial.R;
import com.zygk.qybofficial.config.Constants;
import com.zygk.qybofficial.dao.CommonLogic;
import com.zygk.qybofficial.model.M_AppInfo;
import com.zygk.qybofficial.model.apimodel.APIM_AppInfo;
import com.zygk.qybofficial.util.HttpRequest;
import com.zygk.qybofficial.view.CommonDialog;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import wendu.dsbridge.CompletionHandler;
import wendu.dsbridge.DWebView;
import wendu.dsbridge.OnReturnValue;

/**
 * 承载h5的容器(原生与js有交互的用这个)
 * created by Djy
 * 2017/11/27 0027 上午 11:22
 */
public class H5Activity extends BaseActivity {
  public static final String INTENT_URL = "INTENT_URL";
  private static final String TAG = "";

  private ValueCallback<Uri> mUploadMessage;
  private ValueCallback<Uri[]> mUploadCallbackAboveL;
  ArrayList<ImageItem> selectImageList = new ArrayList<>(); //当前选择的所有图片
  public static final int REQUEST_SELECT_FILE = 100;
  private final static int FILECHOOSER_RESULTCODE = 2;

  private static final int REQ_SCAN = 0x110;

  @BindView(R.id.webView) DWebView webView;

  private String url;
  private CompletionHandler mHandler;

  @Override public void setContentView() {
    setContentView(R.layout.activity_h5);
  }

  @Override public void init() {
    url = getIntent().getStringExtra(INTENT_URL);
    initImagePickerSingle(false);
    initWebView();
    registerReceiver(new String[]{Constants.BROADCAST_MESSAGE_REFRESH });
  }

  private void initWebView() {
    webView.setJavascriptInterface(new JsApi());
    webView.clearCache(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.setWebViewClient(new WebViewClient() {
      @Override public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        Log.d(TAG, "qhj_onPageFinished: "+ DateUtil.now_yyyy_MM_dd_HH_mm_ss_SSS());
        Log.d(TAG, "qhj_url: "+ url);
      }

      @Override public void onLoadResource(WebView view, String url) {
        if (url.contains("/h5/page/plan/week.html")) {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else if (url.contains(".html")) {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
      }

      @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
        //此处根据需求处理逻辑...
        if (url != null && url.startsWith("tel")) {
          String phoneNumber = url.replace("tel://", "");
          Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
        } else {
          view.loadUrl(url);
        }
        return true;
      }

    });
    webView.setWebChromeClient(new WebChromeClient(){
      // For Android 5.0+
      @Override
      public boolean onShowFileChooser(WebView webView,
          ValueCallback<Uri[]> filePathCallback,
          FileChooserParams fileChooserParams) {
        String type = fileChooserParams.getAcceptTypes()[0];
        mUploadCallbackAboveL = filePathCallback;
        picMulti(1, selectImageList);
        return true;
      }

      // For Android 3.0+
      public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        picMulti(1, selectImageList);
      }

      //3.0--版本
      public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMessage = uploadMsg;
        picMulti(1, selectImageList);
      }

      // For Android 4.1
      public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        mUploadMessage = uploadMsg;
        picMulti(1, selectImageList);
      }
    });

    webView.loadUrl(url);
    Log.d(TAG, "qhj_loadUrl: "+ DateUtil.now_yyyy_MM_dd_HH_mm_ss_SSS());
  }

  class JsApi {
    Intent intent;

    @JavascriptInterface void cameraAsyn(JSONObject jsonObject, CompletionHandler handler)
        throws JSONException {
      mHandler = handler;
      if (AndPermission.hasPermission(mContext, Manifest.permission.CAMERA)) {
        intent = new Intent(mContext, CaptureActivity.class);
        intent.putExtra("autoEnlarged", false);
        startActivityForResult(intent, REQ_SCAN);
      } else {
        requestCameraPermission();
      }
    }

    @JavascriptInterface void getDeviceNumberFromJs(JSONObject jsonObject,
        CompletionHandler handler) throws JSONException {
      handler.complete(Hardware.getDeviceID(mContext));
    }

    /**
     * 获取DeviceNumber
     */
    @JavascriptInterface void getDeviceNumber(JSONObject jsonObject, CompletionHandler handler)
        throws JSONException {
      String contactOID = jsonObject.getString("contactOID").replaceAll("-", "");
      // 调用 Handler 来异步设置别名
      pushHandler.sendMessage(pushHandler.obtainMessage(MSG_SET_ALIAS, contactOID));
      handler.complete("");
    }

    /**
     * 清除缓存
     */
    @JavascriptInterface void clearStore(JSONObject jsonObject, CompletionHandler handler)
        throws JSONException {
      runOnUiThread(new Runnable() {
        @Override public void run() {
          webView.clearCache(true);
        }
      });
      handler.complete("");
    }

    /**
     * 退出登录
     */
    @JavascriptInterface void loginOut(JSONObject jsonObject, CompletionHandler handler)
        throws JSONException {
      JPushInterface.deleteAlias(mContext, 0);
      handler.complete("");
    }

    /**
     * 关闭页面
     */
    @JavascriptInterface void setCurClosed(JSONObject jsonObject, CompletionHandler handler)
        throws JSONException {
      finish();
      handler.complete("");
    }
  }

  private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
    @Override public void gotResult(int code, String alias, Set<String> tags) {
      String logs;
      switch (code) {
        case 0:
          // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
          //PreferencesHelper.setSettingBoolean(PreferencesHelper.User.Key.USER_ALIAS, true);
          break;
        case 6002:
          // 延迟 60 秒来调用 Handler 设置别名
          pushHandler.sendMessageDelayed(pushHandler.obtainMessage(MSG_SET_ALIAS, alias),
              1000 * 60);
          break;
      }
    }
  };

  private static final int MSG_SET_ALIAS = 1001;
  private final Handler pushHandler = new Handler() {
    @Override public void handleMessage(Message msg) {
      super.handleMessage(msg);
      switch (msg.what) {
        case MSG_SET_ALIAS:
          // 调用 JPush 接口来设置别名。
          JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null,
              mAliasCallback);
          break;
        default:
          Log.i("setAliasAndTags", "Unhandled msg - " + msg.what);
      }
    }
  };

  //请求拍照权限
  private void requestCameraPermission() {
    AndPermission.with(this)
        .requestCode(102)
        .permission(Manifest.permission.CAMERA)
        .callback(this)
        .start();
  }

  @PermissionYes(102) private void getPermissionYes(List<String> grantedPermissions) {
    Intent intent = new Intent(mContext, CaptureActivity.class);
    intent.putExtra("autoEnlarged", false);
    startActivityForResult(intent, REQ_SCAN);
  }

  @PermissionNo(102) private void getPermissionNo(List<String> deniedPermissions) {
    ToastUtil.showMessage(mContext, "无摄像头权限, 请前往设置中心开启摄像头权限");
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case REQ_SCAN:
          String result = data.getStringExtra("result");
          Log.i("djy", "扫描的二维码内容为=" + result);
          mHandler.complete(result);
          break;
      }
    }else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
        ArrayList<ImageItem> imagesList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        if (imagesList != null) {
          if (mUploadCallbackAboveL != null) {
            onActivityResultAboveL(requestCode, resultCode, data);
          } else if (mUploadMessage != null) {
            for(ImageItem imageItem : imagesList){
              Uri uri = Uri.fromFile(new File(imageItem.path));
              mUploadMessage.onReceiveValue(uri);
            }
            mUploadMessage = null;
          }
        }
      }
    }
  }

  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
    if (requestCode != REQUEST_CODE_SELECT || mUploadCallbackAboveL == null)
      return;
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      ArrayList<ImageItem> imagesList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
      if (imagesList != null) {
        ArrayList<Uri> UriList = new ArrayList<>();
        for(ImageItem imageItem : imagesList){
          Uri uri = Uri.fromFile(new File(imageItem.path));
          UriList.add(uri);
        }
        Uri[] results = new Uri[UriList.size()];
        mUploadCallbackAboveL.onReceiveValue(UriList.toArray(results));
        mUploadCallbackAboveL = null;
      }
    }
  }

  @Override
  protected void handleReceiver(Context context, Intent intent) {
    if (StringUtils.isBlank(intent.getAction()))
      return;
    if (Constants.BROADCAST_MESSAGE_REFRESH.equals(intent.getAction())) {
      webView.callHandler("refresh", new Object[] { "" }, new OnReturnValue() {
        @Override public void onValue(String retValue) {
          Log.d("jsbridge", "call succeed,return value is " + retValue);
        }
      });
    }
  }

  @Override public void onBackPressed() {
    if (!webView.canGoBackOrForward(-1)) {
      finish();
      return;
    }
  }

  @Override protected void onResume() {
    super.onResume();
    common_app_new_version();
  }

  /**
   * 获取当前安卓最新版本
   */
  public void common_app_new_version() {
    CommonLogic.check_app_version_code(mContext, getVersionName(), new HttpRequest.HttpCallback() {
      @Override public void onStart() {

      }

      @Override public void onSucceed(Object obj) {
        APIM_AppInfo res = (APIM_AppInfo) obj;
        M_AppInfo appInfo = res.getResultObj();
        if (appInfo == null) return;
        if (Double.parseDouble(appInfo.getVersionCode().replace(".", "")) > Double.parseDouble(
            getVersionName().replace(".", ""))) {
          CommonDialog.showNewAppVersionDialog(mContext, appInfo, new CommonDialog.OnYesCallback() {
            @Override public void onYesClick() {
              Intent intent = new Intent();
              intent.setAction("android.intent.action.VIEW");
              Uri content_url = Uri.parse(appInfo.getDownloadURL());
              intent.setData(content_url);
              startActivity(intent);
            }
          });
        }
      }

      @Override public void onFailed() {
        ToastUtil.showNetErrorMessage(mContext);
      }

      @Override public void onFinish() {

      }
    });
  }
}
